package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

@Repository
public class DefaultGoodsDao implements GoodsDao{
    @Autowired
    private DataSource dataSource;
    //查询商品信息，一行记录映射为内存中的一个map对象
    public List<Map<String , Object>> findGoods() {
        Connection connection = null;
        Statement statement =null;
        ResultSet resultSet = null;
        try {
            //1.获取连接（从连接池获取）
            connection = dataSource.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.发送sql
            String sql = "select * from tb_goods";
            resultSet = statement.executeQuery(sql);
            //4.处理结果
            List<Map<String,Object>> list = new ArrayList<>();
            while (resultSet.next()){
                Map<String,Object> rowMap = new HashMap<>();
                rowMap.put("id", resultSet.getInt("id"));
                rowMap.put("name", resultSet.getString("name"));
                rowMap.put("remark", resultSet.getString("remark"));
                rowMap.put("createdTime", resultSet.getTimestamp("createdTime"));
                list.add(rowMap);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);//转换为非检查异常（编译时不检测的异常）
        }finally {//5.释放资源
            if (resultSet != null) try {
                resultSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (statement != null) try {
                statement.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (connection != null) try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}
